# -*- coding: utf-8 -*- 
'''
Created on 2011-12-23

@author: TOM
'''
from django.db.models import Q
from django.http import HttpResponse
from django.utils.simplejson import dumps
from django.views.decorators.csrf import csrf_exempt
from website import utils, grids
from website.common import getCompanyTuple, getCURoleId, getEmployeId
from website.constant import SUPER_POWER
from website.employecontrol.models import Employe
from website.resourcecontrol.models import Company, Department, Office, \
    SalaryLevel, Notice, StaticValue, Letters, LettersAttachment, LettersLookupLog
import datetime

#静态值
@csrf_exempt
def static_value_select(request):
    sv_type=request.POST.get('sv_type','')
    if sv_type!='':
        results=StaticValue.objects.filter(sv_type=sv_type).values('code','value')
        return utils.JsonResponse(dumps(list(results)))
    

#公司(校区)管理
@csrf_exempt
def company_list(request):
    '''
        model中 取外键--ForeignKey级联属性，用外键名称+双下划线(__)+映射model中属性   
    '''
    start=request.POST['start']
    limit=request.POST['limit']
    queryset=Company.objects.all();
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id','cn_name','en_name','registered_addr','registered_date',
        'registered_fund','corporation','telephone','parent__id','parent__cn_name')),queryset.count()))


@csrf_exempt
def company_select(request):
    if getCURoleId(request) ==SUPER_POWER :
        try:
            results=Company.objects.all()
            items=[{'id':'','cn_name':'全部'}]
            for res in results:
                item={}
                item['id']=res.id
                item['cn_name']=res.cn_name
                items.append(item)
            return utils.JsonResponse(dumps(items))
        except Exception ,ex:
            print ex
    else:
        company_id = getCompanyTuple(request)[0]
        results=Company.objects.filter(id=company_id).values('id','cn_name')
        return utils.JsonResponse(dumps(list(results)))


@csrf_exempt
def company_select_all(request):
    try:
        results=Company.objects.all()
        items=[{'id':'','cn_name':'全部'}]
        for res in results:
            item={}
            item['id']=res.id
            item['cn_name']=res.cn_name
            items.append(item)
        return utils.JsonResponse(dumps(items))
    except Exception ,ex:
        print ex
    

#43 市场咨询导师 特殊处理，查询所有校区
@csrf_exempt
def company_select_43(request):
    employeId = getEmployeId(request) 
    employe = Employe.objects.get(id=employeId) 
    #43            市场咨询导师,                       市场咨询部经理
    if employe.office.id  in (43,18,41,40,39,38,45,21,15,27)  :
        try:
            results=Company.objects.all()
            items=[{'id':'','cn_name':'全部'}]
            for res in results:
                item={}
                item['id']=res.id
                item['cn_name']=res.cn_name
                items.append(item)
            return utils.JsonResponse(dumps(items))
        except Exception ,ex:
            print ex
    elif getCURoleId(request) ==SUPER_POWER :
        try:
            results=Company.objects.all()
            items=[{'id':'','cn_name':'全部'}]
            for res in results:
                item={}
                item['id']=res.id
                item['cn_name']=res.cn_name
                items.append(item)
            return utils.JsonResponse(dumps(items))
        except Exception ,ex:
            print ex
    else:
        company_id = getCompanyTuple(request)[0]
        results=Company.objects.filter(id=company_id).values('id','cn_name')
        return utils.JsonResponse(dumps(list(results)))


@csrf_exempt
def company_select_base(request):
    if getCURoleId(request) ==SUPER_POWER :
        try:
            results=Company.objects.all()
            items=[]
            for res in results:
                item={}
                item['id']=res.id
                item['cn_name']=res.cn_name
                items.append(item)
            return utils.JsonResponse(dumps(items))
        except Exception ,ex:
            print ex
    else:
        company_id = getCompanyTuple(request)[0]
        results=Company.objects.filter(id=company_id).values('id','cn_name')
        return utils.JsonResponse(dumps(list(results)))
    

@csrf_exempt
def company_save(request):
    company_id=request.POST.get('id','')
    cn_name=request.POST.get('cn_name','')
    en_name=request.POST.get('en_name','')
    registered_addr=request.POST.get('registered_addr','')
    registered_date=request.POST.get('registered_date','')
    registered_fund=request.POST.get('registered_fund','')
    corporation=request.POST.get('corporation','')
    telephone=request.POST.get('telephone','')
    parent_id=request.POST.get('parent__id','')
    try:
        if company_id=='':
            Company.objects.create(cn_name=cn_name,en_name=en_name,registered_addr=registered_addr,registered_date=registered_date,
                                   registered_fund=registered_fund,corporation=corporation,telephone=telephone,parent_id=parent_id)
        else:
            company=Company.objects.get(id=company_id)
            company.cn_name=cn_name
            company.en_name=en_name
            company.registered_addr=registered_addr
            company.registered_date=registered_date
            company.registered_fund=registered_fund
            company.corporation=corporation
            company.telephone=telephone
            company.parent_id=parent_id
            company.save()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))


@csrf_exempt
def company_del(request):
    try:
        ids=request.POST.get('ids','')
        if ids <> '':
            company_ids=ids.split(',')
            for company_id in company_ids:
                Company.objects.get(id=company_id).delete()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))



# 部门管理
@csrf_exempt
def department_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    company_id=request.POST.get('company_id','')
    if company_id =='':
        queryset=Department.objects.all();
    else:
        queryset=Department.objects.filter(company=company_id);
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id','name','leader','parent__id','parent__name',
        'company__id','company__cn_name')),queryset.count()))
 
@csrf_exempt
def department_select(request):
    results=Department.objects.all().values('id','name')
    return utils.JsonResponse(dumps(list(results)))
 
    
@csrf_exempt
def department_save(request):
    department_id=request.POST.get('id','')
    department_name=request.POST.get('name','')
    department_leader=request.POST.get('leader','')
    parent_id=request.POST.get('parent__id',None)
#    company_id=request.POST.get('company__id','')
    try:
        if department_id=='':
            Department.objects.create(name=department_name,leader=department_leader,parent_id=parent_id)
        else:
            department=Department.objects.get(id=department_id)
            department.name=department_name
            department.leader=department_leader
            department.parent_id=parent_id
            department.save()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))

@csrf_exempt
def department_del(request):
    try:
        ids=request.POST.get('ids','')
        if ids <> '':
            department_ids=ids.split(',')
            for department_id in department_ids:
                Department.objects.get(id=department_id).delete()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))   

#职务管理
@csrf_exempt
def office_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    queryset=Office.objects.all();
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id','name','parent__id','parent__name')),queryset.count()))
 
@csrf_exempt
def office_select(request):
    results=Office.objects.all().values('id','name')
    return utils.JsonResponse(dumps(list(results)))
 
    
@csrf_exempt
def office_save(request):
    office_id=request.POST.get('id','')
    office_name=request.POST.get('name','')
    parent_id=request.POST.get('parent__id','')
    try:
        if office_id=='':
            Office.objects.create(name=office_name,parent_id=parent_id)
        else:
            office=Office.objects.get(id=office_id)
            office.name=office_name
            office.parent_id=parent_id
            office.save()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))

@csrf_exempt
def office_del(request):
    try:
        ids=request.POST.get('ids','')
        if ids <> '':
            office_ids=ids.split(',')
            for office_id in office_ids:
                Office.objects.get(id=office_id).delete()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))  

#薪资等级 
@csrf_exempt
def salarylevel_list(request):
    queryset=SalaryLevel.objects.all();
    return utils.JsonResponse(grids.ModelGrid(SalaryLevel).to_grid(queryset))
 
@csrf_exempt
def salarylevel_save(request):
    salary_id=request.POST.get('id','')
    base_salary=request.POST.get('base_salary','')
    performance_salary=request.POST.get('performance_salary','')
    secrecy_salary=request.POST.get('secrecy_salary','')
    traffic_subsidy=request.POST.get('traffic_subsidy','')
    comm_subsidy=request.POST.get('comm_subsidy','')
    salary_grade=request.POST.get('salary_grade','')
    position_level=request.POST.get('position_level','')
    remark=request.POST.get('remark','')
    try:
        if salary_id=='':
            SalaryLevel.objects.create(base_salary=base_salary,performance_salary=performance_salary,secrecy_salary=secrecy_salary,
                                       traffic_subsidy=traffic_subsidy,comm_subsidy=comm_subsidy,salary_grade=salary_grade,
                                       position_level=position_level,remark=remark)
        else:
            salary=SalaryLevel.objects.get(id=salary_id)
            salary.base_salary=base_salary
            salary.performance_salary=performance_salary
            salary.secrecy_salary=secrecy_salary
            salary.traffic_subsidy=traffic_subsidy
            salary.comm_subsidy=comm_subsidy
            salary.salary_grade=salary_grade
            salary.position_level=position_level
            salary.remark=remark
            salary.save()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))

@csrf_exempt
def salarylevel_del(request):
    try:
        ids=request.POST.get('ids','')
        if ids <> '':
            salary_ids=ids.rstrip(',').split(',')
            for salary_id in salary_ids:
                SalaryLevel.objects.get(id=salary_id).delete()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))  



#电子公告
@csrf_exempt
def notice_list(request):
    #电子公告查询
    start=request.POST['start']
    limit=request.POST['limit']
    title=request.POST.get('title','')
    if title =='':
        queryset=Notice.objects.filter(valid_end__gte=datetime.datetime.now(),valid_start__lte=datetime.datetime.now()).order_by('-is_top') ;# gtl 大于    lte小于
    else:
        queryset=Notice.objects.filter(title__contains=title,valid_end__gte=datetime.datetime.now()).order_by('-is_top');
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id','employe_id','employe__name','title','valid_start',
        'valid_end','is_top','content')),queryset.count()))
    
#电子公告
@csrf_exempt
def notice_m_list(request):
    #电子公告管理查询
    start=request.POST['start']
    limit=request.POST['limit']
    title=request.POST.get('title','')
    if title =='':
        queryset=Notice.objects.all().order_by('-is_top') ;
    else:
        queryset=Notice.objects.filter(title__contains=title).order_by('-is_top');
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id','employe_id','employe__name','title','valid_start',
        'valid_end','is_top','content')),queryset.count()))
    

@csrf_exempt
def notice_save(request):
    notice_id=request.POST.get('id','')
    employe_id=getEmployeId(request)
    title=request.POST.get('title','')
    valid_start=request.POST.get('valid_start','')
    valid_end=request.POST.get('valid_end','')
    is_top=request.POST.get('is_top','')
    content=request.POST.get('content','')
    try:
        if notice_id=='':
            Notice.objects.create(employe_id=employe_id,title=title,valid_start=valid_start,valid_end=valid_end,
                                  is_top=is_top,content=content)
        else:
            notice=Notice.objects.get(id=notice_id)
            notice.employe_id=employe_id
            notice.title=title
            notice.valid_start=valid_start
            notice.valid_end=valid_end
            notice.is_top=is_top
            notice.content=content
            notice.save()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))


@csrf_exempt
def notice_del(request):
    try:
        ids=request.POST.get('ids','')
        if ids <> '':
            notice_ids=ids.rstrip(',').split(',')
            for notice_id in notice_ids:
                Notice.objects.get(id=notice_id).delete()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))


#接收电子函件查询
@csrf_exempt
def letters_receive_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    startdate=request.POST.get('startdate','')
    enddate=request.POST.get('enddate','')
    
    CurrentUser=request.session.get('CurrentUser')
    q=Q(receiver__id=CurrentUser.employe.id)
    if startdate<>'':
        q &=Q(send_time__gte=startdate+' 00:00:00')
    if enddate<>'':
        q &=Q(send_time__lte=enddate+' 23:59:59')   

    queryset=Letters.objects.order_by('-send_time').filter(q)[int(start):int(start) + int(limit)];
    items=[]
    for qs in queryset:
        item={}
        formatstr='<font><b>%s</b></b></font>'
        if qs.lookupLog_letters.filter(looker__id=CurrentUser.employe.id).values() :
            formatstr='%s'
        item['id']=qs.id
        item['sender__name']=formatstr % (qs.sender.name,)
        item['title']=formatstr % (qs.title,)
        item['content']= qs.content
        item['send_time']=formatstr % (qs.send_time,)
        items.append(item)
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,items,queryset.count())) 
        
#    queryset=Letters.objects.order_by('-send_time').filter(q);
#    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
#        list(queryset[int(start):int(start) + int(limit)].values('id','sender__name','title','content','send_time'))
#        ,queryset.count())) 
    
#发送电子函件查询
@csrf_exempt
def letters_send_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    startdate=request.POST.get('startdate','')
    enddate=request.POST.get('enddate','')
    
    CurrentUser=request.session.get('CurrentUser')
    q=Q(sender__id=CurrentUser.employe.id)
    if startdate<>'':
        q &=Q(send_time__gte=startdate+' 00:00:00')
    if enddate<>'':
        q &=Q(send_time__lte=enddate+' 23:59:59')    
    queryset=Letters.objects.order_by('-send_time').filter(q)[int(start):int(start) + int(limit)];
    items=[]
    for qs in queryset:
        item={}
        item['id']=qs.id
        item['title']=qs.title
        item['content']=qs.content
        item['send_time']=qs.send_time
        item['receiver_name']=''
        for receiver in qs.receiver.all():
            item['receiver_name']+=receiver.name+';'
        items.append(item)
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,items,queryset.count()))   

#函件附件查找
@csrf_exempt
def letters_attachment_query(request):
    letters_id=request.POST.get('lettersId','')
    results=LettersAttachment.objects.filter(letters=letters_id).values('id','name','path')
    return utils.JsonResponse(dumps({'success':True,'data':list(results)}));
    
#电子函件编写
@csrf_exempt
def letters_save(request): 
    CurrentUser=request.session.get('CurrentUser')
    receiverIds=request.POST.get('receiverIds','')
    title=request.POST.get('title','')
    content=request.POST.get('content','')
    attachments=request.POST.get('attachments','')
    send_date=request.POST.get('sendDate','')
    send_time=request.POST.get('sendTime','')
    try:
        if send_date=='' :
            letters=Letters.objects.create(sender_id=CurrentUser.employe.id,title=title,content=content)
        else:
            letters=Letters.objects.create(sender_id=CurrentUser.employe.id,title=title,content=content,
                    send_time=datetime.datetime.strptime(send_date+' '+send_time,'%Y-%m-%d %H:%M'))
        ids=receiverIds.split(';')
        for _id in ids:
            if _id<>'':
                letters.receiver.add(Employe.objects.get(id=_id))
        
        if attachments<>'':
            _attachments=attachments.split(';')
            for attachment in _attachments:
                name,path=attachment.split(':')
                LettersAttachment.objects.create(name=name,path=path,letters=letters)
        
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))

#电子函件编写
@csrf_exempt
def letters_lookup_save(request): 
    CurrentUser=request.session.get('CurrentUser')
    letters_id=request.POST.get('lettersId','')
    try:
        LettersLookupLog.objects.get_or_create(letters_id=letters_id,looker_id=CurrentUser.employe.id)
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))     




if __name__=='__main__':
    items=[{'id':'1','name':'tom'}]   
    print items
    items.insert(0, {'id':'11','name':'tom1'})
    print items